<template>
  <div>
    <dk-page-diy ref="diyRef" class="m-5">
      <el-button type="primary" icon="FolderChecked" round @click="onSave()">保存</el-button>
      <el-button type="danger" icon="Delete" round @click="onClearDragRule">清 空</el-button>
    </dk-page-diy>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import { createMenu, ruleList } from './rule'
// 自定义组件
import DkWxOauthPage from './components/DkWxOauthPage.vue'
import { getDiyConfig, saveDiyPage } from '@/api/diy'
import { getPlaid } from '@/utils/auth'

defineOptions({
  name: 'WechatOauthPage'
})

const props = defineProps({
  value: {
    default: '',
    type: String
  }
})

// 获取当前组件实例，用于注册组件
const instance = getCurrentInstance()
// 在Vue3中注册全局组件的方式
if (instance) {
  instance.appContext.app.component('DkWxOauthPage', DkWxOauthPage)
}

const diyRef = ref()
const plaid = getPlaid()
const menu = createMenu()

const previewFc = () => {
  diyRef.value.previewFc()
}

const onSave = () => {
  const diyData = {
    config: diyRef.value.getPageConfig(),
    rule: diyRef.value.getRule(),
    float_rule: []
  }
  saveDiyPage('oauth', 'wechat', diyData, plaid).then((res) => {
    ElMessage.success(res.msg)
  })
}

const onClearDragRule = () => {
  diyRef.value.clear()
  ElMessage.success('清空成功')
}

const handleDiyInit = () => {
  diyRef.value.menuList = []
  diyRef.value.addMenu(menu[0])
  diyRef.value.addComponent(ruleList)
  getDiyConfig('oauth', 'wechat', plaid).then((res) => {
    diyRef.value.set(res.data)
  })
}

onMounted(() => {
  handleDiyInit()
})

defineExpose({
  previewFc
})
</script>

<style scoped lang="scss">
.page_diy {
  margin: 0 20px;
}
</style>
